﻿using SIMS.SqlSugarWebApi.Models;
using SqlSugar;
using System.Diagnostics;

namespace SIMS.SqlSugarWebApi
{
    public class DataContext
    {
        public SqlSugarClient db { get; set; }

        private static DbType DbType = DbType.SqlServer;

        private static bool _databaseInitialized = false;

        private static readonly object _lock = new object();

        public DataContext(IConfiguration configuration)
        {
            if (configuration.GetConnectionString("DbType") != null)
            {
                DbType = (DbType)Enum.Parse(typeof(DbType), configuration.GetConnectionString("DbType"));
            }
            var connectionString = configuration.GetConnectionString("DefaultConnection");
            db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = connectionString,
                DbType = DbType, 
                IsAutoCloseConnection = true,
            }, db =>
            {
                db.Aop.OnLogExecuting = (sql, pars) =>
                {
                    var p = UtilMethods.GetNativeSql(sql, pars);
                    Debug.WriteLine(p);
                };
            });

            InitializeDatabaseOnce();
        }

        private void InitializeDatabaseOnce()
        {
            if (!_databaseInitialized)
            {
                lock (_lock)
                {
                    if (!_databaseInitialized)
                    {
                        InitDatabase();
                        _databaseInitialized = true;
                    }
                }
            }
        }

        // 创建数据库和表
        private void InitDatabase()
        {
            db.DbMaintenance.CreateDatabase();

            db.CodeFirst.SetStringDefaultLength(100).InitTables(typeof(Class));
            db.CodeFirst.SetStringDefaultLength(100).InitTables(typeof(Course));
            db.CodeFirst.SetStringDefaultLength(100).InitTables(typeof(Menu));
            db.CodeFirst.SetStringDefaultLength(100).InitTables(typeof(Role));
            db.CodeFirst.SetStringDefaultLength(100).InitTables(typeof(RoleMenu));
            db.CodeFirst.SetStringDefaultLength(100).InitTables(typeof(Score));
            db.CodeFirst.SetStringDefaultLength(100).InitTables(typeof(Student));
            db.CodeFirst.SetStringDefaultLength(100).InitTables(typeof(User));
            db.CodeFirst.SetStringDefaultLength(100).InitTables(typeof(UserRole));
        }
    }
}
